﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AnesSystem.Models;
using System.Collections.ObjectModel;
using AnesSystem.Services;
using System.Windows;
using AnesSystem.Controls.CommonTables.SC.CDTY;
using AnesSystem.Controls;
using System.Windows.Media;
using Common;
using System.Windows.Controls;

namespace AnesSystem.ViewModels
{
    public class ChuFangTableCtrlViewModel : BaseViewModel<ChuFangTableCtrlViewModel>
    {
        #region Variables

        public static Dictionary<string, List<ChuFangItemModel>> chuFangTypeMap = null;
        private static List<ChuFangItemModel> chuFangList;
        private static List<ConfigDrugsModel> configDrugsList;
        private ObservableCollection<ChuFangItemModel> _puTongChuFangList;
        private ObservableCollection<ChuFangItemModel> _jingErChuFangList;
        private ObservableCollection<ChuFangItemModel> _caiLiaoChuFangList;
        private ObservableCollection<ChuFangItemModel> _erKeChuFangList;


        #endregion


        #region Constructor

        public ChuFangTableCtrlViewModel()
        {
            RefResh();
            ConfigDrugsList = DataManager.Instance.ConfigDrugsModelList.ToList();
            //GetChuFangsByPatient(DataManager.Instance.CurrentPatientLink);
        }

        public void RefResh()
        {
            if (DataManager.Instance.CurrentPatientLink != null)
            {
                refreshData(DataManager.Instance.CurrentPatientLink.ChuFangDan.ChuFangList);
            }

        }

        //各种ChuFangList绑定数据
        private void refreshData(List<ChuFangItemModel> chuFangLists)
        {
            chuFangList = chuFangLists;
            if (chuFangList != null)
            {
                chuFangTypeMap = filiterChuFang(chuFangList);
                foreach (var list in chuFangTypeMap.Values)
                {
                    foreach (var item in list)
                    {
                        item.PropertyChanged += initBind;
                    }
                }
                PuTongChuFangList = new ObservableCollection<ChuFangItemModel>(chuFangTypeMap["普通"].ToList());
                JingErChuFangList = new ObservableCollection<ChuFangItemModel>(chuFangTypeMap["精2"].ToList());
                CaiLiaoChuFangList = new ObservableCollection<ChuFangItemModel>(chuFangTypeMap["材料"].ToList());
                ErKeChuFangList = new ObservableCollection<ChuFangItemModel>(chuFangTypeMap["儿科"].ToList());
            }
        }

        private void initBind(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            ChuFangItemModel chuFang = sender as ChuFangItemModel;
            if (e.PropertyName.Equals("DrugName"))
            {
                foreach (var item in configDrugsList)
                {
                    if (chuFang.DrugName == item.Code)
                    {
                        chuFang.DrugName = item.Name;
                        chuFang.DrugShouFeiName = item.PrescriptionName;
                        chuFang.JiLiang = item.Dose.ToString();
                        chuFang.JiLiangUnit = getDrugsUnit(item.UnitName);
                        chuFang.GuiGe = item.Spec;
                        chuFang.GuiGeUnit = getDrugsUnit(item.UnitName);
                        chuFang.RongQiUnit = item.ContainerName;
                        chuFang.UseMethod = item.Usage;
                    }
                }
            }
            if (e.PropertyName.Equals("GuiGe") || e.PropertyName.Equals("JiLiang"))
            {
                if (chuFang.GuiGe != null && !chuFang.GuiGe.Equals("") && float.Parse(chuFang.GuiGe) != 0 && chuFang.JiLiang != null && !chuFang.JiLiang.Equals("") && float.Parse(chuFang.JiLiang) != 0)
                {
                    int spec = (int)(float.Parse(chuFang.GuiGe) * 1000);
                    int dose = (int)(float.Parse(chuFang.JiLiang) * 1000);
                    chuFang.ShuLiang = (dose / spec + (dose % spec == 0 ? 0 : 1) + "").ToString();
                }
            }
            PatientLinkService.Instance.AddUpdate(DataManager.Instance.CurrentPatientLink);
        }

        //药物分类放在Map里
        private Dictionary<string, List<ChuFangItemModel>> filiterChuFang(List<ChuFangItemModel> chuFangList)
        {
            Dictionary<string, List<ChuFangItemModel>> chuFangTypeMap = new Dictionary<string, List<ChuFangItemModel>>();
            List<ChuFangItemModel> puTongChuFangs = new List<ChuFangItemModel>();
            List<ChuFangItemModel> jingErChuFangs = new List<ChuFangItemModel>();
            List<ChuFangItemModel> erKeChuFangs = new List<ChuFangItemModel>();
            List<ChuFangItemModel> caiLiaoFangs = new List<ChuFangItemModel>();
            foreach (var chuFang in chuFangList)
            {
                if (chuFang.ChuFangLeiXing.Equals(Constants.MAZUI_CHUFANGYAO_PUTONG))
                {
                    puTongChuFangs.Add(chuFang);
                }
                else if (chuFang.ChuFangLeiXing.Equals(Constants.MAZUI_CHUFANGYAO_JING2))
                {
                    jingErChuFangs.Add(chuFang);
                }
                else if (chuFang.ChuFangLeiXing.Equals(Constants.MAZUI_CHUFANGYAO_CAILIAO))
                {
                    caiLiaoFangs.Add(chuFang);
                }
                else if (chuFang.ChuFangLeiXing.Equals(Constants.MAZUI_CHUFANGYAO_ERKE))
                {
                    erKeChuFangs.Add(chuFang);
                }
            }
            chuFangTypeMap.Add("普通", puTongChuFangs);
            chuFangTypeMap.Add("精2", jingErChuFangs);
            chuFangTypeMap.Add("材料", caiLiaoFangs);
            chuFangTypeMap.Add("儿科", erKeChuFangs);
            return chuFangTypeMap;
        }


        #endregion

        #region Properties


        public ObservableCollection<ChuFangItemModel> PuTongChuFangList
        {
            get
            {
                return _puTongChuFangList;
            }

            set
            {
                _puTongChuFangList = value;
                RaisePropertyChanged("PuTongChuFangList");
            }
        }

        public ObservableCollection<ChuFangItemModel> JingErChuFangList
        {
            get
            {
                return _jingErChuFangList;
            }

            set
            {
                _jingErChuFangList = value;
                RaisePropertyChanged("JingErChuFangList");
            }
        }

        public ObservableCollection<ChuFangItemModel> CaiLiaoChuFangList
        {
            get
            {
                return _caiLiaoChuFangList;
            }

            set
            {
                _caiLiaoChuFangList = value;
                RaisePropertyChanged("CaiLiaoChuFangList");
            }
        }

        public ObservableCollection<ChuFangItemModel> ErKeChuFangList
        {
            get
            {
                return _erKeChuFangList;
            }

            set
            {
                _erKeChuFangList = value;
                RaisePropertyChanged("ErKeChuFangList");
            }
        }

        public List<ChuFangItemModel> ChuFangList
        {
            get
            {
                return chuFangList;
            }

            set
            {
                chuFangList = value;
                RaisePropertyChanged("ChuFangList");
            }
        }

        public List<ConfigDrugsModel> ConfigDrugsList
        {
            get
            {
                return configDrugsList;
            }

            set
            {
                configDrugsList = value;
                RaisePropertyChanged("ConfigDrugsList");
            }
        }

        public string KaiDanDreoc
        {
            get
            {
                return DataManager.Instance.CurrentPatientLink.ChuFangDan.KaiDanDoc;
            }

            set
            {
                if (DataManager.Instance.CurrentPatientLink != null)
                {
                    DataManager.Instance.CurrentPatientLink.ChuFangDan.KaiDanDoc = value;
                }
                RaisePropertyChanged("KaiDanDreoc");
            }
        }

        public TextBlock FeiBie
        {
            get
            {
                TextBlock tb = new TextBlock();
                tb.Text = DataManager.Instance.CurrentPatientLink.Patient.FeiBie;
                return tb;
            }

            set
            {
                DataManager.Instance.CurrentPatientLink.Patient.FeiBie = value.Text.ToString();
                RaisePropertyChanged("FeiBie");
            }
        }

        #endregion

        #region 依赖属性

        #endregion

        #region Event

        #endregion

        #region Private Methods
        private string getDrugsUnit(string unitCode)
        {
            List<ConfigUnitsModel> ConfigUnitsList = DataManager.Instance.ConfigUnitsModelList.ToList();
            string drugUnit = "mg";
            foreach (var unit in ConfigUnitsList)
            {
                if (unitCode.Equals(unit.Code))
                {
                    drugUnit = unit.Name; 
                }
            }
            return drugUnit;
        }

        #endregion

        #region Public/Protected Methods


        //从麻醉单取药物按钮事件
        public void readAnesDrugs()
        {
            chuFangList = DataManager.Instance.CurrentPatientLink.ChuFangDan.ChuFangList;
            if (chuFangList == null)
            {
                CreatNewChuFang();
            }
            else
            {
                if (MessageBoxCommon.ShowDialog("确定覆盖现有的处方?", MessageBoxCommon.OKCANCLE).Value == true)
                {
                    CreatNewChuFang();
                }
            }
            refreshData(chuFangList);
        }

        private void CreatNewChuFang()
        {
            PatientLinkModel patientLink = DataManager.Instance.CurrentPatientLink;
            List<ChuFangItemModel> chuFangLists = new List<ChuFangItemModel>();
            Dictionary<string, Dictionary<string, ChuFangItemModel>> drugMethodDrugsMap = new Dictionary<string, Dictionary<string, ChuFangItemModel>>();//根据方法类
            List<PatientDrugsModel> drugsList = new List<PatientDrugsModel>();
            DrugsDataCache drugsDataCache = OperationDataPool.Instance.CurOperationData.DrugsDataCache;
            drugsList.AddRange(OperationDataPool.Instance.CurOperationData.DrugsDataCache.AllPatientDrugsList.ToList());
            foreach (var item in drugsDataCache.AnesMedicineMapCodeList.Values.ToList())
            {
                drugsList.AddRange(item);
            }
            
            List<ConfigDrugMethodsModel> ConfigDrugMethodsList = DataManager.Instance.ConfigDrugMethodsModelList.ToList();
            foreach (var drugMethods in ConfigDrugMethodsList)
            {
                drugMethodDrugsMap.Add(drugMethods.Name, new Dictionary<string, ChuFangItemModel>());
            }
            foreach (PatientDrugsModel patientDrugs in drugsList)
            {
                DrugsModel drugs = patientDrugs.Drugs;
                if (patientDrugs.DrugMethod != null && !patientDrugs.DrugMethod.Equals("") && drugs != null)
                {
                    foreach (var item in drugs.Items)
                    {
                        if (item != null && item.Name != null && !item.Name.Equals(""))
                        {
                            item.Name = item.Name.Replace("\u200B","");
                            Dictionary<string, ChuFangItemModel> chuFangTypeMap = drugMethodDrugsMap[patientDrugs.DrugMethod];
                            if (chuFangTypeMap.ContainsKey(item.Name) && chuFangTypeMap[item.Name] != null)
                            {
                                ChuFangItemModel chuFang = chuFangTypeMap[item.Name];
                                //chuFang.JiLiang = (float.Parse(chuFang.JiLiang) + item.Dose).ToString();
                                //if (chuFang.GuiGe != null && !chuFang.GuiGe.Equals("") && float.Parse(chuFang.GuiGe) != 0)
                                //{
                                //    int spec = (int)(float.Parse(chuFang.GuiGe) * 1000);
                                //    int dose = (int)(float.Parse(chuFang.JiLiang) * 1000);
                                //    chuFang.ShuLiang = (dose / spec + (dose % spec == 0 ? 0 : 1) + "").ToString();
                                //}
                            }
                            else
                            {
                                ConfigDrugsModel configDrugs = new ConfigDrugsModel();
                                foreach (var configDrugsTemporary in configDrugsList)
                                {
                                    if (configDrugsTemporary.Name != null && configDrugsTemporary.Name.Equals(item.Name))
                                    {
                                        configDrugs = configDrugsTemporary;
                                        break;
                                    }
                                    else
                                    {
                                        configDrugs = null;
                                    }
                                }
                                ChuFangItemModel chuFang = new ChuFangItemModel();
                                try
                                {
                                    chuFang.DrugName = item.Name;
                                    chuFang.JiLiang = item.Dose.ToString();
                                    chuFang.UseMethod = patientDrugs.DrugMethod;
                                    chuFang.JiLiangUnit = item.Unit;
                                    chuFang.GuiGeUnit = item.Unit;
                                    chuFang.ShuLiang = "1";
                                    if (configDrugs != null)
                                    {
                                        chuFang.DrugId = configDrugs.Code;
                                        chuFang.GuiGe = configDrugs.Spec;
                                        chuFang.GuiGeUnit = item.Unit;
                                        if (chuFang.GuiGe != null && !chuFang.GuiGe.Equals("") && float.Parse(chuFang.GuiGe) != 0)
                                        {
                                            int spec = (int)(float.Parse(chuFang.GuiGe) * 1000);
                                            int dose = (int)(float.Parse(chuFang.JiLiang) * 1000);
                                            chuFang.ShuLiang = (dose / spec + (dose % spec == 0 ? 0 : 1) + "").ToString();
                                        }
                                        chuFang.RongQiUnit = configDrugs.ContainerName;
                                        chuFang.DrugShouFeiName = configDrugs.PrescriptionName;

                                        if (configDrugs != null && configDrugs.PrescriptionName != null)
                                        {
                                            foreach (   var prescriptionType in  DataManager.Instance.ConfigPrescriptionTypesModelList.ToList())
                                            {
                                                if (prescriptionType.Code.Equals(configDrugs.PrescriptionTypeCode))
                                                {
                                                    chuFang.ChuFangLeiXing = prescriptionType.Name;
                                                }
                                            }
                                        }else
                                        {
                                            chuFang.ChuFangLeiXing = configDrugs.PrescriptionName != null ? configDrugs.PrescriptionName : "普通";
                                        }
                                    }
                                    if (int.Parse(patientLink.Patient.Nl.Replace("岁", "")) < 14)
                                        chuFang.ChuFangLeiXing = Constants.MAZUI_CHUFANGYAO_ERKE;
                                    chuFang.BeiZhu = "";
                                }
                                catch (Exception ex)
                                {
                                    Common.LogHelper.Error(this.GetType(), ex);
                                }
                                chuFangTypeMap.Add(item.Name, chuFang);
                            }
                        }
                    }
                }
                else
                {
                    MessageBoxCommon.ShowDialog("读取药失败，请检查" + drugs.FullName + "名称是否正确！", MessageBoxCommon.OK);
                }
            }

            foreach (Dictionary<string, ChuFangItemModel> chuFangTypeMap in drugMethodDrugsMap.Values)
            {
                foreach (var chuFang in chuFangTypeMap.Values)
                {
                    if (chuFang != null)
                    {
                        chuFangLists.Add(chuFang);
                    }
                }
            }
            chuFangList = chuFangLists;
            patientLink.ChuFangDan.ChuFangList = chuFangList;
            if (DataManager.Instance.CurrentPatientLink.Id != null)
            {
                PatientLinkService.Instance.Update(DataManager.Instance.CurrentPatientLink);
            }

        }


        public void AddChuFang(string type)
        {
            ChuFangItemModel item = new ChuFangItemModel();
            item.DrugId = "";
            item.ChuFangLeiXing = type;
            item.DrugShouFeiName = "";
            item.GuiGe = "";
            item.GuiGeUnit = "";
            item.JiLiang = "";
            item.JiLiangUnit = "";
            item.ShuLiang = "1";
            item.RongQiUnit = "";
            item.UseMethod = "";
            item.BeiZhu = "";

            chuFangList.Add(item);
            PatientLinkService.Instance.Update(DataManager.Instance.CurrentPatientLink);
            refreshData(chuFangList);
        }
        public void RemoveChuFang(ChuFangItemModel item)
        {
            chuFangList.Remove(item);
            PatientLinkService.Instance.Update(DataManager.Instance.CurrentPatientLink);
            refreshData(chuFangList);
        }


        public List<FrameworkElement> CreateChuFangPrintData()
        {

            List<ChuFangDanCtrl> chuFangDanList = new List<ChuFangDanCtrl>();
            List<FrameworkElement> chuFangPageList = new List<FrameworkElement>();

            //取出四种类型的处方
            foreach (string key in chuFangTypeMap.Keys)
            {
                List<ChuFangItemModel> chuFangTypeList = chuFangTypeMap[key].ToList();
                int numDan = chuFangTypeList.Count;
                for (int i = 0; i < (numDan % 5 == 0 ? numDan / 5 : numDan / 5 + 1); i++)
                {
                    ChuFangDanCtrl chuFangDan = new ChuFangDanCtrl();
                    List<ChuFangItemModel> chufanglist = new List<ChuFangItemModel>();
                    chuFangDan._chuFangDanType.Content = key;
                    chuFangDan.DataContext = DataManager.Instance.CurrentPatientLink;
                    int num = (i + 1) * 5 > numDan ? numDan : ((i + 1) * 5);
                    for (int j = i * 5; j < num; j++)
                    {
                        chufanglist.Add(chuFangTypeList[j]);
                    }
                    chuFangDan._chuFangList.ItemsSource = chufanglist;
                    chuFangDanList.Add(chuFangDan);
                }
            }

            int valPage = chuFangDanList.Count;
            for (int i = 0; i < (valPage % 2 == 0 ? valPage / 2 : valPage / 2 + 1); i++)
            {
                ChuFangPageCtrl chuFangPage = new ChuFangPageCtrl();
                List<FrameworkElement> chufangdanlist = new List<FrameworkElement>();
                int num = (i + 1) * 2 > valPage ? valPage : ((i + 1) * 2);
                for (int j = i * 2; j < num; j++)
                {
                    chufangdanlist.Add(chuFangDanList[j]);
                }
                chuFangPage._chuFangDanList.ItemsSource = chufangdanlist;
                chuFangPageList.Add(chuFangPage);
            }
            return chuFangPageList;
        }

        #endregion

        #region EventHandlers

        #endregion
    }
}
